package org.snusmumr.android.media;

import java.util.ArrayList;

import org.snusmumr.android.media.data.ContactAPI;
import org.snusmumr.android.media.data.LentItemsOperation;
import org.snusmumr.android.media.data.MediaColumns;
import org.snusmumr.android.media.util.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class SelectContactForLendActivity extends Activity {
	private static final String TAG = SelectContactForLendActivity.class.getSimpleName();
	private SimpleCursorAdapter cursorAdapter;
	private ListView contactsView;
	private long[] itemIds;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		final Bundle extras = getIntent().getExtras();
		itemIds = extras.getLongArray(Constants.KEY_ID);
		Log.i(TAG, "passed item IDs: " + Utils.arrayToString(itemIds));
		
		setTitle(R.string.select_contact_dlg_title);
		setContentView(R.layout.select_contact_dlg);
		contactsView = new ListView(this);
		contactsView.setId(android.R.id.list);
		LinearLayout scroll = (LinearLayout) findViewById(R.id.select_contact_scroll);
		scroll.addView(contactsView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		final EditText filterEdit = (EditText) findViewById(R.id.select_contact_search_view);
		filterEdit.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				Cursor c = cursorAdapter.runQueryOnBackgroundThread(s);
				cursorAdapter.getCursor().close();
				cursorAdapter.changeCursor(c);
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			
			@Override
			public void afterTextChanged(Editable s) {}
		});
		
		final ContactAPI contacts = ContactAPI.getAPI();
		contacts.setContentResolver(getContentResolver());
		final String displayNameColumn = contacts.getMetaData().displayName();
		Cursor cursor = contacts.getContactsCursor(null, null, displayNameColumn);
		cursorAdapter = new SimpleCursorAdapter(this, 
				android.R.layout.simple_list_item_1, 
				cursor, new String[]{MediaColumns.DISPLAY_NAME}, 
				new int[]{android.R.id.text1});
		cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
			@Override
			public Cursor runQuery(CharSequence constraint) {
				String selection = null;
				if(constraint.length() > 1)
					selection = "lower(" + MediaColumns.DISPLAY_NAME + ") like '%"+
					constraint.toString().toLowerCase() + "%'";
				Cursor cursor = contacts.getContactsCursor(selection, null, displayNameColumn); 
				return cursor;
			}
		});
		contactsView.setAdapter(cursorAdapter);
		contactsView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				cursorAdapter.getCursor().move(position-cursorAdapter.getCursor().getPosition());
				int indexId = cursorAdapter.getCursor().getColumnIndex(MediaColumns._ID);
				int indexName = cursorAdapter.getCursor().getColumnIndex(MediaColumns.DISPLAY_NAME);
				invokeLend(cursorAdapter.getCursor().getString(indexId), 
						cursorAdapter.getCursor().getString(indexName), true);
			}
		});
		
		Button createContact = (Button) findViewById(R.id.btn_create_contact);
		createContact.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//TODO show create user dialog
				final String displayName = filterEdit.getText().toString();
				Log.i(TAG, "contact name: " + displayName);
				if(Utils.isEmpty(displayName)) {
					Toast.makeText(SelectContactForLendActivity.this, 
							"_Please enter contact name", Toast.LENGTH_SHORT).show();
					return;
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(SelectContactForLendActivity.this);
				builder.setMessage("_Are you sure you want to create a new contact?")
				.setPositiveButton(R.string.btn_dlg_save, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						long id = contacts.insertContact(displayName);
						if(id > 0) {
							invokeLend(String.valueOf(id), displayName, false);
						}
					}
				}).setNegativeButton(R.string.btn_dlg_cancel, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).show();
			}
		});
	}
	
	private void invokeLend(final String contactId, final String displayName, final boolean forceShowConfirmation) {
		if(forceShowConfirmation)
			new AlertDialog.Builder(this)
	        .setIcon(android.R.drawable.ic_dialog_alert)
	        .setTitle(R.string.confirm_lend_title)
	        .setMessage(Utils.format(getResources(), R.string.confirm_lend_msg, displayName))
	        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	            	doLend(contactId, displayName);
	            }
	        })
	        .setNegativeButton(android.R.string.no, null)
	        .show();
		else
			doLend(contactId, displayName);
	}
	
	protected void onPause() {
		super.onPause();
		
		if(! cursorAdapter.getCursor().isClosed())
			cursorAdapter.getCursor().close();
	};
	
	@Override
	protected void onResume() {
		super.onResume();
		
		cursorAdapter.getCursor().requery();
	}

	private void doLend(final String contactId, final String displayName) {
		if(itemIds == null) {
			Log.w(TAG, "No itemIds passed. Do nothing");
			return;
		}
		
		ArrayList<Long> selected = new ArrayList<Long>(itemIds.length);
		for(int i=0; i<itemIds.length; i++) {
			selected.add(itemIds[i]);
		}
		Boolean lentResult = new LentItemsOperation(
				SelectContactForLendActivity.this, 
				contactId, displayName, selected).execute();
		if(Boolean.TRUE.equals(lentResult))
			finish();
	}
}
